package dao;


import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;

import static java.lang.Class.forName;

public class DBbean {
    private Connection con;      // 与数据库的连接
    private Statement stmt;
    private PreparedStatement pstmt;    // 用于执行sql语句，并返回结果集合
    private ResultSet rs;          // 结果集合

    // 获得连接
    public Connection getConnection() {
        if(con == null) {
            try {
                Class.forName("com.mysql.jdbc.Driver") ;
                String url = "jdbc:mysql://www.smx98.cn:3306/ebookstore";
                String user = "root";
                String pw = "5647089";
                con = DriverManager.getConnection(url+"?user="+user+"&password="+pw+"&useUnicode=true&characterEncoding=utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return con;
    }

    // 执行查询操作
    public ResultSet executeQuery(String sql, ArrayList params) throws Exception {
        if(con == null) {
            throw new Exception("未连接数据库");
        }

        pstmt = con.prepareStatement(sql);  // 执行sql语句
        if(params != null) {
            Iterator it = params.iterator();
            int idx = 1;
            while(it.hasNext()) {
                String tmp = (String)it.next();
                pstmt.setString(idx, tmp);
                idx++;
            }
        }
        System.out.println(sql);

        return pstmt.executeQuery();
    }

    public int executeUpdate(String sql, ArrayList params) throws Exception{
        if(con == null) {
            throw new Exception("未连接数据库");
        }
        pstmt = con.prepareStatement(sql);
        int idx = 1;
        if(params != null) {
            Iterator it = params.iterator();
            while(it.hasNext()) {
                String tmp = (String)it.next();
                pstmt.setString(idx, tmp);
                idx++;
            }
        }
        System.out.println(sql);
        return pstmt.executeUpdate();
    }

    public void close() {
        try {
            if(rs != null) {
                rs.close();
            }
            if(stmt != null) {
                stmt.close();
            }
            if(pstmt != null) {
                pstmt.close();
            }
            if(con != null) {
                con.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
